package com.yunshan.common.utils;


import com.alibaba.fastjson2.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 字符串工具类
 *
 * @author liaoyz
 * @version v1.0
 * @date 2021/12/20 18:17
 * @change 2021/12/20 18:17 liaoyz@v1.0 创建
 **/
@Slf4j
public class StringUtil {

    /**
     * 功能：获取UUID并去除“-”
     */
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("-", "");
    }

    /**
     * 时间处理，返回当前时间前几天
     *
     * @param date
     * @return
     */
    public static Date dateHandleDay(Date date, int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, i);
        return calendar.getTime();
    }

    /**
     * 对字符串md5加密
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) {
        return DigestUtils.md5Hex(str);
    }

    /***
     * String 转date
     * @param date
     * @return
     * @throws ParseException
     */
    public static Date stringToDate(String date, String type) throws ParseException {
        if (type == null) {
            type = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(type);

        return sdf.parse(date);
    }

    /***
     * date 转 String
     * @param date
     * @param type
     * @return
     */
    public static String dateToString(Date date, String type) {
        if (type == null) {
            type = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(type);

        return formatter.format(date);
    }


    /**
     * 判断是否为空/空串
     * @param str 判断的字符串
     * @return {@link boolean}
     * @author liaoyz
     * @date 2022/04/10 12:38 修改
     **/
    public static boolean isBlank(String str) {
        return null == str || "".equals(str.trim());
    }

    /**
     * 判断不为空/空串
     * @param str 判断的字符串
     * @return {@link boolean}
     * @author liaoyz
     * @date 2022/04/10 12:40 新增
     **/
    public static boolean notBlank(String str) {
        return str != null && !"".equals(str.trim());
    }

    private static final Long NUM = (26L + 26L + 10);
    private static final Random RANDOM = new Random();

    private static final char[] CHAR_ARRAY = {'7', '8', '9', '0', '1', '5', '6', '2', '3', '4',
            'a', 'B', 'c', 'D', 'E', 'F', 'G', 'h', 'I', 'J', 'K', 'L', 'm', 'n', 'O', 'P', 'Q', 'R', 'S', 'T', 'u', 'V', 'W', 'X', 'y', 'Z',
            'A', 'b', 'C', 'd', 'e', 'f', 'g', 'H', 'i', 'j', 'k', 'l', 'M', 'N', 'o', 'p', 'q', 'r', 's', 't', 'U', 'v', 'w', 'x', 'Y', 'z',};

    /**
     * 加强版
     * 62位加密
     *
     * @param number 加密的数据
     * @return {@link String}
     * @author liaoyz
     * @date 2021/12/20 18:02
     * @version v1.0
     * @change 2021/12/20 18:02 liaoyz@v1.0 创建
     **/
    public static String digit62EnCodePlus(long number) {
        StringBuilder sb = new StringBuilder();
        int num = CHAR_ARRAY.length;
        if (number == 0) {
            sb.append(CHAR_ARRAY[0]);
        } else {
            while (number != 0) {
                int t = (int) (number % num);
                sb.insert(0, CHAR_ARRAY[t]);
                number = number / NUM;
            }
        }
        return sb.toString();
    }

    /**
     * 加强版
     * 62位解密
     *
     * @param code 加密后的数据
     * @return {@link String}
     * @author liaoyz
     * @date 2021/12/20 18:02
     * @version v1.0
     * @change 2021/12/20 18:02 liaoyz@v1.0 创建
     **/
    public static Long digit62DnCodePlus(String code) {
        int num = CHAR_ARRAY.length;
        if (code == null || code.trim().length() == 0) {
            throw new RuntimeException("解密信息不能为空");
        }
        long res = 0L;
        for (char charInStr : code.toCharArray()) {
            Integer index = null;
            for (int i = 0; i < CHAR_ARRAY.length; i++) {
                if (charInStr == CHAR_ARRAY[i]) {
                    index = i;
                    break;
                }
            }
            if (index == null) {
                throw new RuntimeException("错误的code");
            }
            res = res * num + index;
        }
        return res;
    }

    /**
     * 62位加密+2位随机
     *
     * @param number 加密的数据
     * @return {@link String}
     * @author liaoyz
     * @date 2021/12/20 18:02
     * @version v1.0
     * @change 2021/12/20 18:02 liaoyz@v1.0 创建
     **/
    public static String digit62(long number) {
        StringBuilder sb = new StringBuilder();
        // int i = 0;
        if (number == 0) {
            sb.append(0);
        } else {
            while (number != 0) {
                long t = number % NUM;
                if (t >= 0 && t < 10) {
                    sb.insert(0, (char) (t + '0'));
                    // i++;
                } else if (t < 36) {
                    sb.insert(0, (char) (t + 'a' - 10));
                    // i++;
                } else {
                    sb.insert(0, (char) (t + 'A' - 36));
                }
                number = number / NUM;
            }
        }
        // 加两位随机数，防止敌人猜测到我们的算法，随意生成用来获取信息
        sb.append(String.format("%02d", RANDOM.nextInt(100)));
        return sb.toString();
    }

    /**
     * @return java.util.List<java.util.List < T>>
     * @author liudan
     * @description 按指定大小，分隔集合，将集合按规定个数分为n个部分
     * @Param list
     * @Param len
     * @date 15:57 2019/7/19 0019
     **/
    public static <T> List<List<T>> splitList(List<T> list, int len) {
        if (list == null || list.isEmpty() || len < 1) {
            return Collections.emptyList();
        }

        List<List<T>> result = new ArrayList<>();

        int size = list.size();
        int count = (size + len - 1) / len;

        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, (Math.min((i + 1) * len, size)));
            result.add(subList);
        }
        return result;
    }

    public static boolean checkArrayString(String str) {
        try {
            JSONArray.parseArray(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 字符替换 *
     *
     * @param str       原字符串
     * @param prefixNum 头部字符保留数量
     * @param suffixNum 尾部字符保留数量
     * @return 新字符串
     */
    public static String replaceWithStar(String str, int prefixNum, int suffixNum) {
        if (str == null) {
            return null;
        }
        int length = str.length();
        if (prefixNum + suffixNum > length) {
            return str;
        }
        StringBuilder resultStr = new StringBuilder(str.substring(0, prefixNum));
        for (int i = 0; i < length - prefixNum - suffixNum; i++) {
            resultStr.append("*");
        }
        resultStr.append(str, length - suffixNum, length);
        return resultStr.toString();
    }

    /**
     * 移除表情符号
     * @param str 输入字符串
     * @return {@link String}
     * @author liaoyz
     * @date 2022/02/15 17:58
     * @version v1.0
     * @change 2022/02/15 17:58 liaoyz@v1.0 创建
     **/
    public static String removeEmoji(String str) {
        if (str == null) {
            return null;
        }
        return str.replaceAll("[^\\u0000-\\uFFFF]", "");
    }

    /**
     * 整数去零
     * 如 100.00 -> 100
     * @param val 值
     * @return {@link String}
     * @author liaoyz
     * @date 2022/04/20 22:20
     **/
    public static String feeRemoveZero(BigDecimal val) {
        return feeRemoveZero(val.toString());
    }

    /**
     * 整数去零
     * 如 100.00 -> 100
     * @param val 值
     * @return {@link String}
     * @author liaoyz
     * @date 2022/04/20 22:20
     **/
    public static String feeRemoveZero(String val) {
        return val.replaceAll("\\.00", "");
    }

    /**
     * 去除id标识
     * 例如：【id】测试奶卡 -> 测试奶卡
     * @param str 需处理字符串
     * @return {@link String}
     * @author liaoyz
     * @date 2022/04/27 13:36
     **/
    public static String removeIdSign(String str) {
        int index = str.indexOf("】");
        if (index != -1) {
            return str.substring(index + 1);
        }
        return str;
    }

    /**
     * 加密手机号，中间四位用星号替换
     *
     * @param phoneNumber 手机号
     * @return 加密后的手机号
     */
    public static String encryptPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.length() != 11) {
            throw new IllegalArgumentException("手机号格式不正确");
        }
        return phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7);
    }
}
